package com.atguigu.spzx.manager.listenner;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.spzx.manager.mapper.CategoryMapper;
import com.atguigu.spzx.model.dto.product.CategoryExcelDto;
import com.atguigu.spzx.model.pojo.product.Category;

import java.util.ArrayList;
import java.util.List;

public class EasyExcelListener extends AnalysisEventListener<CategoryExcelDto> {
    private CategoryMapper categoryMapper;
    // 临时存储数据
    private List<Category> datas = new ArrayList<>();

    // spring 构造器注入
    public EasyExcelListener(CategoryMapper categoryMapper) {
        this.categoryMapper = categoryMapper;
    }

    // 读取文件数据
    @Override
    public void invoke(CategoryExcelDto t, AnalysisContext analysisContext) {
        Category category = new Category();
        category.setName(t.getName());
        category.setStatus(t.getStatus());
        category.setId(t.getId());
        category.setImageUrl(t.getImageUrl());
        category.setParentId(t.getParentId());
        category.setOrderNum(t.getOrderNum());
        datas.add(category);
        // 每100个数据存一次数据库
        if (datas.size() >= 100) {
            categoryMapper.insert(datas);
            datas.clear();
        }
    }

    // 最后的处理
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (!datas.isEmpty()) {
            categoryMapper.insert(datas);
            datas.clear();
        }
    }
}
